package com.recharge.job;

import com.recharge.AsyncTaskService;
import com.recharge.callback.AbsCallBackService;
import com.recharge.domain.TradeMerchant;
import com.recharge.domain.TradeNotify;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeMerchantMapper;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.mapper.TradeNotifyMapper;
import com.recharge.utils.ProcessResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by CAOQI on 2017/1/8.
 */
@Service
public class NotifyService {
    @Autowired
    private TradeNotifyMapper tradeNotifyMapper;

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @Autowired
    private ITradeMerchantMapper itradeMerchantMapper;

    @Resource(name = "callBackMap")
    private Map<String,AbsCallBackService> callMap;

    @Value("${notifyNum}")
    private Integer notifyNum ;

    @Autowired
    private AsyncTaskService asyncTaskService;

    public void notifyService(){
        TradeNotify tradeNotify = new TradeNotify();
        tradeNotify.setNotifyStatus((short) 1);
        List<TradeNotify> tradeNotifies = tradeNotifyMapper.selectToNotify(tradeNotify, notifyNum);

        if (CollectionUtils.isNotEmpty(tradeNotifies)){
            for(TradeNotify t: tradeNotifies){
                try {
                    TradeOrder tr = iTradeOrderMapper.selectByOrderId(t.getOrderId());

                    if (tr ==null){
                        logger.warn("orderId : {} ,is null",t.getOrderId());
                    }
                    logger.info("orderId : {} will notify",tr.getOrderId());

                    String callType = null;
                    if (StringUtils.equals("2881802543",tr.getMerId())){
    //                    天猫的订单
                        callType = "TM";
                    }else{
                        callType ="NORMAL";
                    }

                    TradeMerchant tradeMerchant = itradeMerchantMapper.selectById(tr.getMerId());

                    asyncTaskService.callBack(t,tr,tradeMerchant,callType);
                } catch (Exception e) {
                    logger.info("notify error",e);
                }
            }
        }
    }
}
